package cs.rsa.ts14.foxtrot.app;

import cs.rsa.ts14.framework.LineType;
import cs.rsa.ts14.framework.ReportBuilder;
import cs.rsa.ts14.framework.TimesagLineProcessor;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Iterator;

class FoxyTimesag {
    private TimesagLines tslines;
    private final TimesagLineProcessor tlp;
    private final PrintStream outstream;

    public FoxyTimesag(Builder builder) throws IOException {
        tlp = builder.getTimesagProcessor();
        outstream = builder.getOutputStream();
        tslines = builder.getTimesagLines();
    }

    public void run() throws FoxyException {

        try (TimesagLines lines = tslines){

            tlp.beginProcess();

            processEachLine(lines);

            tlp.endProcess();

            printFinalReport();

        } catch (FoxyException fe) {
            throw fe;
        } catch (Exception e) {
            throw new FoxyException("unknown error, processing input, " + e.getMessage());
        }

    }

    private void processEachLine(Iterator<String> it) throws FoxyException {
        while (it.hasNext()) {
            String line = it.next();
            LineType linetype = tlp.process(line);
            validateProcessing(linetype);
        }
    }

    private void validateProcessing(LineType linetype) throws FoxyException {
        if (linetype == LineType.INVALID_LINE)
            throw new FoxyException("Error in file: " + tlp.lastError());
        if(linetype == LineType.INVALID_SEQUENCE)
            throw new FoxyException("Error in file: " + tlp.lastError());
    }

    private void printFinalReport() {
        outstream.println(tlp.getReport());
    }

    public static Builder newBuilder(File file) {
        return new Builder(file);
    }


    public static Builder newBuilder(TimesagLines lines) {
        return new Builder(lines);
    }

    public static void main(String[] args)  {

        if (args.length != 2) {
            System.err.println("Usage: Timesag [type] [timesag file]");
            System.err.println("  type must be one of (W, C, T).");
            System.err.println("  timesag file must obey the specified format.");
            System.exit(-1);
        }

        try {

            String reportTypeString = args[0];
            File file = new File(args[1]);
            FoxyTimesag fts = FoxyTimesag.newBuilder(file).setReportType(reportTypeString).build();
            fts.run();

        } catch (IOException ioe) {

            System.out.println(ioe.getMessage());
            System.exit(-1);

        } catch (Exception e) {

            e.printStackTrace();
            System.out.println(e.getMessage());
            System.exit(-1);

        }
    }

}

